package com.yykj.backstage.all.service.impl;

import com.yykj.backstage.all.dto.HospitalAgreementSearchDTO;
import com.yykj.backstage.all.model.entity.HospitalAgreement;
import com.yykj.backstage.all.model.repository.HospitalAgreementRepository;
import com.yykj.backstage.all.service.HospitalAgreementService;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class HospitalAgreementServiceImpl implements HospitalAgreementService {
    @Override
    public HospitalAgreement editHospitalAgreement(HospitalAgreement hospitalAgreement) {
        HospitalAgreement agreement;
        if (hospitalAgreement.getType() == null
                || (1 != hospitalAgreement.getType()
                && 2 != hospitalAgreement.getType()
                && 3 != hospitalAgreement.getType()
                && 4 != hospitalAgreement.getType()
                && 5 != hospitalAgreement.getType())
                || hospitalAgreement.getShowType() == null
                || (1 != hospitalAgreement.getShowType()
                && 2 != hospitalAgreement.getShowType())) {
            throw new NormalException(ResultEnums.PARAM_ERROR,"type和showType必输");
        }
        if (hospitalAgreement.getId() != null && hospitalAgreement.getId() > 0) {
            agreement = repository.findById(hospitalAgreement.getId()).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
        } else {
            agreement = new HospitalAgreement();
        }
        LocalObjectUtil.copyNullValue(hospitalAgreement, agreement);
        return repository.save(hospitalAgreement);
    }

    @Override
    public List<HospitalAgreement> listHospitalAgreement() {
        return repository.findAll();
    }

    @Override
    public HospitalAgreement viewHospitalAgreement(HospitalAgreementSearchDTO searchDTO) {
        if (searchDTO.getId() != null && searchDTO.getId() > 0) {
            return repository.findById(searchDTO.getId()).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
        } else {
            return repository.findFirstByTypeOrderByAddTimeDesc(searchDTO.getType());
        }

    }

    private HospitalAgreementRepository repository;

    @Autowired
    public void setRepository(HospitalAgreementRepository repository) {
        this.repository = repository;
    }
}
